package it.okkam.longwell.ui.command;

import it.okkam.webid.certificate.model.GenerateCertificate;
import it.okkam.webid.certificate.model.GenerateCertificateException;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;

import edu.mit.simile.longwell.login.CheckLogin;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.InjectionManager;
import edu.mit.simile.longwell.ui.command.CommandBase;

/**
 * 
 * Create a certificate and allow users to download the certificate
 *
 */

public class SaveCertificateCommand extends CommandBase {
	CheckLogin check=null;
    private String targetFileName = null;
    private String sourceFile= null;
	final protected String m_template;
	public static boolean userInput = false;
	protected ServletContext 	context;
	VelocityContext vcContext = null;
	HashMap<String, String> userForSession = new HashMap<String, String>();
	/**
	 * @param injectionManager
	 */
	public SaveCertificateCommand(InjectionManager injectionManager, String template) {
		super(injectionManager);
		m_template = template;
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.flair.IFlairCommand#execute(edu.mit.simile.flair.FlairMessage)
	 */
	public void execute(FlairMessage msg) throws ServletException {
		
		int keySize = Integer.parseInt(msg.m_request.getParameter("keysize"));	
		String uris =  msg.m_request.getParameter("webid");
		int maxAge = Integer.parseInt(msg.m_request.getParameter("days"));
		String fullName = msg.m_request.getParameter("fullname");
		String o = msg.m_request.getParameter("o");
		String ou = msg.m_request.getParameter("ou");
		String cn = msg.m_request.getParameter("cn");
		String password = msg.m_request.getParameter("password");
	
		try {
		GenerateCertificate webid = new GenerateCertificate();
		webid = webid.generate(fullName, o,ou,cn,keySize, uris, new Date(), GenerateCertificate.createDeltaDate(maxAge));
		
		KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance("PKCS12", Security.getProvider("BC"), new KeyStore.PasswordProtection(password.toCharArray()));
		KeyStore ks = ksBuilder.getKeyStore();

		ks.setKeyEntry(fullName, webid.getPrivateKey(), password.toCharArray(), new Certificate[] { webid.getCertificate() });
		
		ServletContext ServletContext = msg.m_servlet.getServletContext();
        String path = ServletContext.getRealPath("/WEB-INF");
        System.out.println(path);
        File newUserFile = new File(path+"/tmp/"+fullName+".p12");
        newUserFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(newUserFile);
        ks.store(fos, password.toCharArray());
        fos.close();

        msg.m_request.setAttribute("sourceFile", newUserFile.getAbsolutePath());
        msg.m_request.setAttribute("targetFileName", newUserFile.getName());
        
        processRequest(msg);
   
	} catch (GenerateCertificateException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (KeyStoreException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (NoSuchAlgorithmException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (CertificateException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
//	reqDisp.forward(request,response);
		catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}
	/*
	 * Modified from the Okkam-Register  Upload Java File
	 */ 
    /**
     * Download the created certificate from the browser. 
     * The certificate will not be stored in the server
     */
    protected void processRequest(FlairMessage msg)
    throws ServletException, IOException {

            targetFileName = (String)msg.m_request.getAttribute("targetFileName");
            sourceFile = (String)msg.m_request.getAttribute("sourceFile");
            /*System.out.println("targetFileName is: "+targetFileName);
        System.out.println("sourceFile is: "+sourceFile);*/

            File                f        = new File(sourceFile);
            int                 length   = 0;
            ServletOutputStream op       = msg.m_response.getOutputStream();
            ServletContext      context  =  msg.m_servlet.getServletConfig().getServletContext();
            String              mimetype = context.getMimeType( sourceFile );

            //
            //  Set the response and go!
            //
            //
            msg.m_response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
            msg.m_response.setContentLength( (int)f.length() );
            msg.m_response.setHeader( "Content-Disposition", "attachment; filename=\"" + targetFileName + "\"" );


            //
            //  Stream to the requester.
            //
            byte[] bbuf = new byte[sourceFile.length()];
            DataInputStream in = new DataInputStream(new FileInputStream(f));

            while ((in != null) && ((length = in.read(bbuf)) != -1))
            {
                op.write(bbuf,0,length);
            }

            in.close();
            op.flush();
            op.close();

            if(f.exists())
                f.delete();



    }

}	
